package cn.gbase.jiangsu.data.transfer.validation;

import java.lang.reflect.Method;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.nutz.aop.interceptor.AbstractMethodInterceptor;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;

import cn.gbase.jiangsu.data.transfer.bean.BaseDto;
import cn.gbase.jiangsu.data.transfer.validation.annotation.AnnotationValidation;

/**
 * 基于注解的验证用拦截器
 * 
 * 该拦截器主要用于方法参数的验证，要求该方法中必须有一个 Errors 类型的参数(允许为空)，当验证完成后会向这个参数赋值
 * 
 */
@IocBean(name = "validationInterceptor")
public class ValidationInterceptor extends AbstractMethodInterceptor {

	private static AnnotationValidation av = new AnnotationValidation();

	/**
	 * 方法调用前进行拦截，遍历参数进行验证
	 */
	@Override
	public boolean beforeInvoke(Object obj, Method method, Object... args) {
		Errors es = new Errors();
		BaseDto formData = null;
		for (Object argObj : args) {
			if (argObj instanceof BaseDto) {
				formData = (BaseDto) argObj;
				av.validate(argObj, es);
			}
		}
		// check未通过，则跳回输入页面
		if (es.errorCount() > 0) {
			StringBuilder sb = new StringBuilder();
			Iterator<String> ite = es.getErrorsList().iterator();
			while (ite.hasNext()) {
				sb.append("*").append(ite.next()).append("<br/>");
			}

			HttpServletRequest request = Mvcs.getReq();
			request.setAttribute("errmsg", sb.toString()); // 错误信息
			request.setAttribute("formdata", formData); // 表单数据
			throw new RuntimeException();
		}

		return true;
	}
}
